<template>
  <div>

    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
      <el-form-item label="程序名称">
        <el-input v-model="searchForm.applicationName"></el-input>
      </el-form-item>
      <el-form-item label="板材类型">
        <el-input v-model="searchForm.boardType"></el-input>
      </el-form-item>
      <el-form-item label="板材厚度">
        <el-input v-model="searchForm.plateThickness"></el-input>
      </el-form-item>
      <el-form-item label="是否完成">
        <el-input v-model="searchForm.completed"></el-input>
      </el-form-item>
      <el-form-item label="接收时间">
        <el-date-picker v-model="searchForm.beginReceptionTime" type="date" placeholder="开始日期"></el-date-picker>
        <el-date-picker v-model="searchForm.endReceptionTime" type="date" placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="完成时间">
        <el-date-picker v-model="searchForm.beginCompletionTime" type="date" placeholder="开始日期"></el-date-picker>
        <el-date-picker v-model="searchForm.endCompletionTime" type="date" placeholder="结束日期"></el-date-picker>
      </el-form-item>


    </el-form>

    <div style="display: flex; justify-content: space-between; padding: 10px 10px 0; margin-bottom: 10px;">
  <!-- 左侧按钮组（确认完成按钮） -->
  <div class="button-group">
    <el-button type="primary" @click="handleConfirmComplete">
      <i class="el-icon-check"></i>确认完成
    </el-button>
  </div>
  
  <!-- 右侧按钮组（搜索/重置） -->
  <div>
    <el-button type="primary" @click="handleSearch">搜索</el-button>
    <el-button @click="handleReset">重置</el-button>
  </div>
</div>
    

      


    <el-table :data="dataForm" :loading="loadingTable" style="width: 100%;" max-height="660px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" :index="1" label="序号"></el-table-column>
      <el-table-column prop="applicationName" label="程序名称"></el-table-column>
      <el-table-column prop="boardType" label="板材类型"></el-table-column>
      <el-table-column prop="plateThickness" label="板材厚度"></el-table-column>
      <el-table-column prop="runsNum" label="运行次数" width="100"></el-table-column>
      <el-table-column prop="receptionTime" label="接收时间"></el-table-column>
      <el-table-column prop="completionTime" label="完成时间"></el-table-column>
      <el-table-column prop="completed" label="是否完成"></el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template slot-scope="scope">
          <div style="display: flex; justify-content: space-around">
            <el-button type="text" @click="handleView(scope.row)"><i class="el-icon-view"></i>查看</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="pageNum" :page-sizes="[10, 20]" :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    <FormComponent ref="formComponent" @refresh="handleSearch" />
    <DetailComponent ref="detailComponent" />
    <ImportComponent ref="importComponent" @refresh="handleSearch" />
  </div>
</template>

<script>
import {
  getList,
  deleteBydSpecialPojectDataById,
} from "@/views/subdev/special/helper/api";
import { getSelectLaserData, batchUpdate } from "./helper/api";
import { getToken } from "@/utils/auth"; // 导入获取token的方法
import dayjs from "dayjs";
import FormComponent from "@/views/subdev/special/form.vue";
import ImportComponent from "@/views/subdev/special/import.vue";
import DetailComponent from '@/views/subdev/special/detail.vue'

export default {
  components: {
    FormComponent,
    DetailComponent,
    ImportComponent,
  },
  data() {
    return {
      selectedRows: [], // 存储被选中的行
      dataForm: [],
      searchForm: {
        applicationName: "",
        boardType: "",
        plateThickness: "",
        completed: "",
        beginReceptionTime: "",
        endReceptionTime: "",
        beginCompletionTime: "",
        endCompletionTime: "",
      },
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      loadingSearch: false,
      loadingTable: false,
      loadingEdit: false,
      loadingDelete: false,
      loadingView: false,
      deleteVisible: false
    };
  },
  mounted() {
    this.handleSearch()
  },
  beforeDestroy() {
  },
  methods: {
     // 确认完成按钮点击事件
     handleConfirmComplete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请先勾选需要确认完成的项目");
        return;
      }
      
      // 检查是否包含已完成项目
      const hasCompleted = this.selectedRows.some(row => row.completed === "已完成");
      if (hasCompleted) {
        this.$message.warning("选中的项目包含已完成的项，请重新选择");
        return;
      }
      
      this.$confirm(`确定要将选中的 ${this.selectedRows.length} 项标记为"已完成"吗?`, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const updateData = this.selectedRows.map(row => ({
          id: row.id,
          completed: "已完成",
        }));
        
        // 添加加载状态
        this.loadingConfirm = true;
        
        // 添加token到请求头
        const config = {
          headers: {
            Authorization: "Bearer " + getToken()
          }
        };
        
        // 调用批量更新接口
        batchUpdate(updateData, config)
          .then(res => {
            console.log('res', res)
            if (res.code === 200) {
              this.$message.success(`成功更新 ${res.data} 个项目状态`);
              this.handleSearch(); // 刷新列表
              this.selectedRows = []; // 清空选择
            } else {
              this.$message.error(res.msg || "更新失败");
            }
          })
          .catch(error => {
            console.error('更新失败:', error);
            this.$message.error("更新失败，请重试");
          })
          .finally(() => {
            this.loadingConfirm = false;
          });
      }).catch(() => {
        // 用户取消操作
        this.$message.info("已取消操作");
      });
    },
    handleSelectionChange(selectedRows) {
      console.log('selectedRows', selectedRows)
      this.selectedRows = selectedRows; // 存储选中行数据
    },
    handleSearch() {
      this.loadingSearch = true;
      this.loadingTable = true;
      getList(this.searchForm, this.pageNum, this.pageSize)
        .then((res) => {
          console.log('res', res)
          res.rows.forEach((element) => {
            element.orderDate = element.beginReceptionTime ? dayjs(element.beginReceptionTime).format(
              "YYYY-MM-DD"
            ) : '暂无';
            element.deliveryDate = element.endReceptionTime ? dayjs(element.endReceptionTime).format(
              "YYYY-MM-DD"
            ) : '暂无';
            element.changeDate = element.beginCompletionTime ? dayjs(element.beginCompletionTime).format(
              "YYYY-MM-DD"
            ) : '暂无';
            element.shippingDate = element.endCompletionTime ? dayjs(element.endCompletionTime).format(
              "YYYY-MM-DD"
            ) : '暂无';
          });
          // this.total = res.total;
          // this.tableData = res.rows;

          setTimeout(() => {
            this.loadingSearch = false;
            this.loadingTable = false;
          });

        })
        .catch((error) => {
          console.error("搜索失败:", error);
          setTimeout(() => {
            this.loadingSearch = false;
            this.loadingTable = false;
          });
        });

      getSelectLaserData(this.searchForm, this.pageNum, this.pageSize).then(res => {
        this.dataForm = res.rows
        this.total = res.total;
        // this.tableData = res.rows;
        console.log('this.dataForm', this.dataForm)
      })
    },
    handleReset() {
      this.searchForm = {
        applicationName: "",
        boardType: "",
        plateThickness: "",
        completed: "",
        beginReceptionTime: "",
        endReceptionTime: "",
        beginCompletionTime: "",
        endCompletionTime: "",
      };
      this.handleSearch();
    },
    handleAdd() {
      this.$refs.formComponent.showDialog();
    },
    handleImport() {
      this.$refs.importComponent.showDialog();
    },
    handleExport() {
      this.$confirm('是否根据搜索条件导出所有内容?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.download(`/bydspecialPoject/downExcel`,
          {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            ...this.searchForm
          },
          `订单数据_${new Date().getTime()}.xlsx`,)
      })
    },
    handleView(row) {
      console.log('row', row)
      const pdfUrl = row.attachmentAddress; // 获取PDF的原始地址
      // 发送带token的请求获取PDF
      fetch(pdfUrl, {
        method: 'GET',
        headers: {
          Authorization: "Bearer " + getToken() // 携带token
        }
      })
        .then(response => {
          // 检查请求是否成功
          if (!response.ok) {
            throw new Error(`请求失败，状态码: ${response.status}`);
          }
          // 将响应转换为blob（二进制文件）
          return response.blob();
        })
        .then(blob => {
          // 创建临时URL用于预览
          const tempPdfUrl = URL.createObjectURL(blob);
          // 打开新窗口预览PDF
          window.open(tempPdfUrl);
        })
        .catch(error => {
          console.error('PDF预览失败:', error);
          this.$message.error('预览失败，请检查权限或网络'); // 提示用户错误
        });
      // window.open(row.attachmentAddress)
      // this.loadingView = true;
      // 查看逻辑
      // this.$refs.detailComponent.showDialog(row);
      // this.loadingView = false;
    },
    handleDelete(ids) {
      this.loadingDelete = true;
      // 删除逻辑
      deleteBydSpecialPojectDataById(ids)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success("删除成功！");
          } else {
            this.$message.success("删除失败！");
            console.error(res.msg);
          }
          this.deleteVisible = false;
          this.handleSearch();
        })
        .catch((err) => {
          console.error(err);
        });
      this.loadingDelete = false;
    },
    handleEdit(row) {
      this.loadingEdit = true;
      this.$refs.formComponent.showDialog(row);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleSearch();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.handleSearch();
    },
  },
};
</script>

<style lang="scss" scoped>
/* 样式 */
::v-deep .el-form-item {
  margin-bottom: 5px !important;
}

::v-deep .el-form {
  padding: 10px;
}

.btmOption {
  padding: 5px 15px;
  display: flex;
  justify-content: space-between;
}

::v-deep .el-table__body-wrapper {
  min-height: 550px;
}


.pagination {
  position: absolute;
  bottom: 0px;
  width: 100%;
  background: #fff;
}

.button-group {
  padding: 10px;
  display: flex;
  gap: 10px;
}
</style>
